<template>
  <div class="video-center">
    <div class="storeSelect">
      <selectStore @handleChange="optionChange"/>
    </div>
    <el-row v-if="!ActiveXObject" :gutter="10" class="video__plugin__list"  v-loading="isLoad">
      <el-col class="plugin__list" v-for="(item, index) in videoList" :key="index" :span="6">
        <div class="plugin__item" @click="handlePlugin(item)">
          <div>{{format(new Date())}}</div>
          <div>{{item.name}}</div>
        </div>
      </el-col>
    </el-row>
    <div v-else style=" margin-top: 10px; min-height: 200px; text-align: center; line-height: 38px;">
      <p>请点击下面链接下载插件，安装时请关闭浏览器，并使用IE浏览器预览！</p>
      <a :href="`${actionData}/pc/static/webs/codebase/WebComponentsKit-32.exe`" download="WebComponentsKit-32">点击下载WebComponentsKit-32</a>
      <br>
      <a :href="`${actionData}/pc/static/webs/codebase/WebComponentsKit-32.exe`" download="WebComponentsKit-64">点击下载WebComponentsKit-64</a>
    </div>
    <div id="divPlugin" class="plugin" ></div>
  </div>
</template>
<script>
  import { formatDate } from '../../../utils/format-data'
  import { mapMutations, mapGetters } from 'vuex'
  import {queryDeviceManage, getDeviceInfo} from '@/api/deviceManage'
  import selectStore from '../components/selectStore'

  export default {
    name: 'videoSurveillance',
    components: {
      selectStore
    },
    data() {
      return {
        actionData: "http://124.70.17.33",
        ActiveXObject: false,
        isLoad: true,
        pageSize:99999,
        currentPage: 1,
        tableData: [],
        orgSeq: '',
        hkvInfo: {
          ip: '10.100.6.48',//海康威视摄像头/硬盘录像机的ip地址
          port: '80',//海康威视摄像头/硬盘录像机的端口
          username: 'admin',//海康威视摄像头/硬盘录像机的用户名
          password: '1234567890q',//海康威视摄像头/硬盘录像机的密码
          channels: [],//海康威视摄像头/硬盘录像机的通道
        },
        iRtspPort: 0,
        NVRItem: {},
        storeName: '',
      }
    },
    computed: {
      ...mapGetters([
        'videoList',
      ])
    },
    methods: {
      ...mapMutations( [ 'increment' ] ),
      //门店选择
      optionChange(val){
        this.orgSeq=val[val.length-1];
        this.getData();
      },
      /**
      * 時間格式化
       * @param val 传入的时间
      * */
      format(val) {
        return formatDate(val, 'yyyy-MM-dd hh:mm:ss')
      },
      /**
       * 打开当前监控
       * @param val 当前视频信息
      * */
      handlePlugin(val) {
        this.$router.push({
          name: 'videoPlugin',
          params: {
            value: val,
            item: this.NVRItem
          },
        });
      },
      onLogin(item) {
        let that = this;
        let szDeviceIdentify = `${item.deviceIp}_${item.devicePort}`
      let iRetLogin =  WebVideoCtrl.I_Login(item.deviceIp, 1, item.devicePort, item.deviceUser, item.deivcePassword, {
          async: false,
          success: (xmlDoc) => { //成功的回调函数
            // console.log(xmlDoc);
            setTimeout(function () {
              that.getChannelInfo(item);
              that.getDevicePort(szDeviceIdentify);
            }, 10);
          },
          error: (e) => { //失败的回调函数
            that.$message.error("登陆失败，请检查NVR设备！");
          }
        });
        if (-1 === iRetLogin) {
          console.log (iRetLogin, '以登陆过');
          let iRet =WebVideoCtrl.I_Logout(szDeviceIdentify);
          iRet === 0 ?  that.onLogin(item) : that.$message.error("退出失败！");
        }
      },
      /**
      * 获取设备端口号
      * @param szDeviceIdentify 设备标识
      * */
      getDevicePort: function (szDeviceIdentify) {
        let oPort =WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
        this.iRtspPort = oPort.iRtspPort;
      },
      // 获取通道，实际上可以根据自己的项目，获取数字通道，模拟通道，零通道中的一个或多个，不用全部获取（提高效率）
      getChannelInfo (item) {
        let that = this;
        let szDeviceIdentify = `${item.deviceIp}_${item.devicePort}`
        that.hkvInfo.channels = [];
        let nAnalogChannel = 0;
        // 数字通道
        WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
          async: false,
          success: function (xmlStr) {
            console.log(xmlStr);
            let oChannels = $(xmlStr).find("InputProxyChannelStatus");
            $.each(oChannels, function (i) {
              let {id,name,online} = {
                id: $(this).find("id").eq(0).text(),
                name: $(this).find("name").eq(0).text(),
                online: $(this).find("online").eq(0).text()};
              if ("false" === online) {// 过滤禁用的数字通道
                return true;
              }
              if ("" === name) {
                name = "IPCamera" + ((id - nAnalogChannel) <= 9 ? "0" + (id - nAnalogChannel) : (id - nAnalogChannel));
              }
              let obj = {
                id:id,
                name:name,
              };
              that.hkvInfo.channels.push(obj)
              that.increment({
                list: that.hkvInfo.channels
              });
            });
            if (that.hkvInfo.channels.length === 0) {
              that.$message.warning("当前无可用预览通道！");
            }
            that.isLoad = false;
          },
          error: function () {
            WebVideoCtrl.I_GetLastError()
          }
        });
      },
      //设备初始化
      videoInitPlugin() {
        let iSnp = WebVideoCtrl.I_SupportNoPlugin();
        let iChe = WebVideoCtrl.I_CheckPluginInstall();
        console.log(iSnp, iChe);
        if (!!window.ActiveXObject || "ActiveXObject" in window) {
          if(!iSnp && iChe) {
           this.ActiveXObject = true;
            return
          }
        }
        this.ActiveXObject = false;
        this.initPlugin()
      },
      initPlugin() {
        let that = this;
        WebVideoCtrl.I_InitPlugin('100%', '100%', {
          iWndowType: 1,
          bDebugMode: true,
          bWndFull: true,
          cbInitPluginComplete() {
            WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
            that.getData()
          }
        })
      },
      //获取门店设备信息
     async getData() {
       this.isLoad = true;
         let {records} = await queryDeviceManage({
         size: this.pageSize,
         current: this.currentPage,
         condition: {
           orgSeq: this.orgSeq,
         }
       });
       let list = records.filter(item => {
         return !!item.typeCode && item.typeCode === '004'
       });
       this.NVRItem = list[0]

       list.length === 1 ? this.onLogin(list[0]) :  list.length > 1 ? this.$message.warning('包含多个NVR，请选择具体的门店！') : this.$message.warning('该门店无NVR设备！')
     }
    },
    mounted() {
      this.videoInitPlugin();
    },
  created() {
    this.orgSeq=JSON.parse(localStorage.getItem('logininfo')).orgList[0].orgSeq||'';
  }
  }
</script>
<style lang="less" scoped>
  .storeSelect {
    height: 50px;
    width: 100%;
    font-size: 13px;
    line-height: 50px;
    border-bottom: 1px solid #DCDFE6;
    display: flex;
    align-items: center;
  }
  .plugin{
    padding: 10px 0;
    max-height: calc(100% - 100px);
    width: 100%;
  }
  .video__plugin__list{
    margin-top: 10px;
    min-height: 200px;
    .plugin__list{
      margin-bottom: 10px;
      .plugin__item{
        background: #797979;
        height: 200px;
        padding: 10px;
        position: relative;
        border: 1px solid #797979;
        cursor: pointer;
        &:hover{
          border: 1px solid #FFCC00;
        }
        div{
          color: #fff;
          &:first-child{
            text-align: right;
          }
          &:last-child{
            position: absolute;
            bottom: 10px;
            right: 10px;
          }
        }
      }
    }

  }
</style>
